package com.dstats.fragments;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.adapter.TIMatchsAdapter;
import com.dstats.Constants;
import com.dstats.MatchDetailsActivity;
import com.dstats.R;
import com.entities.Match;
import com.entities.MatchDetailed;
import com.fetch.Fetch;
import com.fetch.FetchMatchsDetails;

public class TIGamesFragment extends Fragment {

	ListView listView;
	ProgressBar pBar;
	private ProgressDialog pDialog;
	   public View onCreateView(LayoutInflater inflater, ViewGroup container,
	             Bundle savedInstanceState) {
	         View rootView = inflater.inflate(R.layout.ti_matchs_layout, container, false);
	         listView = (ListView) rootView.findViewById(R.id.listViewTIMatchs);
	         pBar = (ProgressBar) rootView.findViewById(R.id.progressBarTI);
	         pBar.setVisibility(View.INVISIBLE);
	         new FetchMatchs(0).execute();
	        
	        
	         return rootView;
	   }
	   
	   private class FetchMatchs extends Fetch{

			private long matchIdToStart;
		
			@Override
			protected void onPreExecute() {
			super.onPreExecute();
			pBar.setIndeterminate(true);
			pBar.setVisibility(View.VISIBLE);
			}
			public FetchMatchs(long matchIdToStart) {
				this.matchIdToStart = matchIdToStart;
			}
			
			@Override
			protected List<NameValuePair> getParams() {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair(Constants.KEY, Constants.apiKey));
				params.add(new BasicNameValuePair(Constants.LEAGUE_ID, "600"));
				params.add(new BasicNameValuePair("min_players", "5"));
				if(matchIdToStart!=0){
					params.add(new BasicNameValuePair("start_at_match_id", String.valueOf(matchIdToStart)));
				}
				return params;
			}

			@Override
			protected String getUrl() {
				return "https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/V001/";
			}
			@Override
			protected void onPostExecute(JSONObject result) {
			super.onPostExecute(result);
			
			JSONObject json;
			try {
				json = result.getJSONObject(Constants.RESULT);
				List<Match> newMatchList = Match.getMatchsFromJSONArray(json.getJSONArray(Match.TAG_MATCHES));
				 listView.setAdapter(new TIMatchsAdapter(getActivity(), newMatchList));
				 listView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(final AdapterView<?> adapter, View arg1, final int arg2,
							long arg3) {
						Long match_id = ((Match) adapter.getItemAtPosition(arg2)).getMatch_id();
						MatchDetailed matchDetailed = MatchDetailed.allMatchsDetailed.get(match_id);
						if(matchDetailed==null){
						new FetchMD(String.valueOf(match_id)).execute();
						} else {
						new StartDetailedMatch(matchDetailed).execute();
							
						}
						
					}
				});
			} catch (JSONException e) {
				e.printStackTrace();
			}
			pBar.setVisibility(View.INVISIBLE);
			
			}
	   }
	   
	    private class FetchMD extends FetchMatchsDetails {

			

			public FetchMD(String matchId) {
				super(matchId);
			}
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				
				pDialog = new ProgressDialog(getActivity());
		        pDialog.setMessage(getString(R.string.plsWait));
		        pDialog.setIndeterminate(true);
		        pDialog.setCancelable(false);		        
		        pDialog.show();
				
			}
			
			@Override
			protected void onPostExecute(JSONObject result) {
				super.onPostExecute(result);
				
				try {
					MatchDetailed match = new MatchDetailed(result.getJSONObject(Constants.RESULT));
					MatchDetailsActivity.setMatch(match);
					if(pDialog!=null)
					pDialog.dismiss();
					Intent i = new Intent(getActivity(), MatchDetailsActivity.class);
					startActivity(i);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
	    	
	    }
	    
	    private class StartDetailedMatch extends AsyncTask<Void, Void, Intent>{

	    	private MatchDetailed matchDetailed;
	    	
	    	public StartDetailedMatch(MatchDetailed matchDetailed) {
				this.matchDetailed = matchDetailed;
			}
	    	
	    	@Override
	    	protected void onPreExecute() {
				super.onPreExecute();
				
				pDialog = new ProgressDialog(getActivity());
		        pDialog.setMessage(getString(R.string.plsWait));
		        pDialog.setIndeterminate(true);
		        pDialog.setCancelable(false);		        
		        pDialog.show();
	    	}
	    	
			@Override
			protected Intent doInBackground(Void... params) {
				MatchDetailsActivity.setMatch(matchDetailed);

				
				Intent i = new Intent(getActivity(), MatchDetailsActivity.class);
				return i;
			}
			
			@Override
			protected void onPostExecute(Intent result) {
				if(pDialog!=null) {
					pDialog.dismiss();
				}
				startActivity(result);
			}
	    	
	    }
	   
	
}
